<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods:POST,GET,PUT,DELETE'); // 允许请求的类型
include("controller/CustomerController.php");
include("controller/ManufacturerController.php");
include("controller/BagController.php");
include("controller/RentalController.php");
include("ReturnHelper.php");

$method = $_SERVER['REQUEST_METHOD'];

if (array_key_exists("s", $_GET)) {
    $path = $_GET["s"];
    $split = explode('/', $path);
    $isList = (count($split) === 2);
    $controllerStr = $split[0];
    $id = null;
    if ($isList === false) {
        $id = $split[1];
    }

    $controllerClassName = ucfirst($controllerStr . "Controller");
    $controller = new $controllerClassName;

    $data = null;

    switch ($method) {
        case "GET":
            {
                if ($isList) {
                    $data = $controller->getList();
                } else {
                    $data = $controller->get($id);
                }
            }
            break;
        case "POST":
            {
                $raw = file_get_contents('php://input');
                $obj = json_decode($raw, true);
                $data = $controller->post($obj);
            }
            break;
        case "PUT":
            {
                $raw = file_get_contents('php://input');
                $obj = json_decode($raw, true);
                $data = $controller->update($id, $obj);
            }
            break;
        case "DELETE":
            {
                $data = $controller->delete($id);
            }
            break;
    }
    // 返回json
    ReturnHelper::response($data);
}
else if (array_key_exists("t", $_GET)) {
    $path = $_GET["t"];
    $split = explode('/', $path);
    $controllerStr = $split[0];

    $controllerClassName = ucfirst($controllerStr . "Controller");
    $controller = new $controllerClassName;

    $functionName = $split[1];
    array_splice($split, 0, 2);
    array_splice($split, count($split) - 1, 1);

    $data = null;
    switch ($method) {
        case "GET":
        case "DELETE":
            // 调用相应的方法并传入参数
            $data = call_user_func_array(array($controller, $functionName), $split);
            break;
        case "POST":
        case "PUT":
            $raw = file_get_contents('php://input');
            $obj = json_decode($raw, true);
            // 将post或PUT的obj作为最后一个参数传入
            array_push($split, $obj);
            $data = call_user_func_array(array($controller, $functionName), $split);
            break;
    }
    // 返回json
    ReturnHelper::response($data);
}



